package com.le.buddha.service.impl;

import cn.hutool.core.util.ObjectUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nls.client.AccessToken;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.le.buddha.conf.RedisKey;
import com.le.buddha.service.IAliYunService;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AliYunServiceImpl implements IAliYunService {

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Resource
    private RedisTemplate<String, String> template;

    @Override
    public synchronized String getAccessToken() {
        try {
            String aliYunToken = template.opsForValue().get(RedisKey.aliToken);
            //            if( Boolean.FALSE.equals(redisTemplate.hasKey(RedisKey.aliyuntoken))){
            if (ObjectUtil.isNull(aliYunToken)) {
                AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
                accessToken.apply();
                aliYunToken = accessToken.getToken();
                long expireTime = accessToken.getExpireTime() * 1000;
                long sysDate = new Date().getTime();
                //计算时间差
                long cha = expireTime - sysDate - 1000;
                template.opsForValue().set(RedisKey.aliToken, aliYunToken, cha, TimeUnit.MICROSECONDS);
                return aliYunToken;
            } else {
                //  return redisTemplate.opsForValue().get(RedisKey.aliyuntoken);
                return aliYunToken;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean sendSMS(String phone, String captcha) {

        try {


            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                     .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                     .build());

            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // Region ID
                     .credentialsProvider(provider)

                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                     .setEndpointOverride("dysmsapi.aliyuncs.com")
                     )
                    .build();
            JSONObject templateParam = new JSONObject();
            templateParam.put("code", captcha);
            templateParam.put("phone", phone);
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers(phone)
                    .templateParam(templateParam.toString())
                      .build();

             CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
             SendSmsResponse resp = response.get();
            if (resp.getBody().getCode().equals("OK")) {
                return true;
            } else {
                log.error("调用阿里云短信异常错误码==={}", resp.getBody().getCode());

            }


        } catch (Exception e) {
            log.error("调用阿里云短信异常==={}", e.getMessage());
        }

        return false;
    }


}
